#include <iostream>
#include <string>
#include <map>
#include <memory>
#include <vector>
#include <optional>
#include <fstream> // Needed for creating test file
#include <stdexcept> // For stoi error handling
#include <unistd.h> // For usleep/sleep
#include <future>      // For std::future (ThreadPool)
#include <chrono>      // For std::chrono::milliseconds
#include <numeric>     // For std::iota
#include <mutex>       // For std::mutex (priority test)
#include <algorithm>   // For std::sort, std::accumulate (priority test)
#include "config.h"
//#include "JSONHandler/JSONHandler.h"
//#include "Release/include/JSONHandler.h"
#include "Release/include/Module/ErrorHandler/signalhandler_linux.h"
#include "Release/include/InterfaceSDK.h"
#include "Release/include/Module/ThreadModule/ThreadPool.h"
#include "Release/include/Module/RandomProvider/RandomProvider.h"
#include "Module/JSONHandler/JSONHandler.h"
#include "Module/JSONHandler/JsonFlatMapAccessor.h"
#include "Module/JSONHandler/JSONNode.h"
// A custom signal handler function
void customSignalHandler(int signum, siginfo_t *info, void *context) {
    std::cout << "Caught signal " << signum << std::endl;

    // Get the instance of the Exceptionhandler
    Exceptionhandler& handler = Exceptionhandler::get_instance();

    // Get and print stack trace
    std::vector<std::string> stackTrace;
    handler.getStackTrace(stackTrace);
    std::cout << "Stack Trace:" << std::endl;
    for (const auto& line : stackTrace) {
        std::cout << line << std::endl;
    }
    

    // Get and print system information
    std::string sysInfo;
    if (handler.getSysinfo(sysInfo)) {
        std::cout << "System Info: " << sysInfo << std::endl;
    }

    // Get and print CPU usage information
    std::string cpuUsageInfo;
    if (handler.getProcessCPUUsage(cpuUsageInfo)) {
        std::cout << "CPU Usage Info: " << cpuUsageInfo << std::endl;
    }

    // Get and print resource usage information
    std::vector<std::string> resourceUsage;
    if (handler.getProcessResourceUsage(resourceUsage)) {
        std::cout << "Resource Usage:" << std::endl;
        for (const auto& usage : resourceUsage) {
            std::cout << usage << std::endl;
        }
    }

    // Get and print thread status information
    std::vector<ThreadInfo> threadStatus;
    if (handler.getThreadStatus(threadStatus)) {
        std::cout << "Thread Status:" << std::endl;
        for (const auto& thread : threadStatus) {
            std::cout << "Thread ID: " << thread.tid << ", Name: " << thread.comm << ", State: " << thread.state << std::endl;
        }
    }
}

// --- 全局数据结构 (用于线程池优先级测试) ---
struct TaskExecutionInfo {
    int priority;
    std::chrono::high_resolution_clock::time_point startTime;
    std::thread::id threadId; // 记录执行线程ID (可选)
};

std::vector<TaskExecutionInfo> g_taskExecutionLog;
std::mutex g_logMutex;
// -----------------------------------------

/**
 * @brief 全面测试 JSONHandler 的访问器功能，包括修改、状态管理和版本控制。
 * @param handler 一个已经通过文件成功加载了 JSON 数据的 JSONHandler 实例引用 (non-const).
 * @param originalFilePath 用于加载 handler 的原始文件路径，供 reset 测试使用。
 *
 * 该函数系统地测试 JSONHandler 的各项功能:
 * - 基本信息: MainKey, 初始 Dirty 状态, 初始数据版本。
 * - 扁平化访问/修改 (flatMapAccessor): containsKey, getValue, getAllValue, setValueByPath (包括版本和 Dirty 状态检查)。
 * - 节点访问/修改 (nodeAccessor): const/non-const 访问, 赋值修改 (包括版本和 Dirty 状态检查)。
 * - 跨访问器缓存验证: 测试一个访问器的修改是否能被另一个访问器的缓存正确处理（基于版本号）。
 * - 文件操作: saveToFile (检查 Dirty 状态重置)。
 * - 状态管理: clear, reset (检查 Dirty 状态和版本号重置)。
 */
void testJsonHandlerFeatures(JSONHandler& handler, const std::string& originalFilePath) { 
    std::cout << "\n===== 开始全面测试 JSONHandler 功能 (包括版本控制) =====\n" << std::endl;

    const std::string testOutputFile = "test_output.json";
    const std::string testCreatedConfigFile = "test_created_config.json";
    // const std::string testRngFile = "test_rng.json"; // Removed, declared in main now

    // --- 0. 基本信息 --- 
    std::cout << "--- 0. 基本信息 --- " << std::endl;
    std::cout << "  主键 (MainKey): " << handler.getMainKey() << std::endl;
    std::cout << "  初始 JSON (string): \n" << handler.getJsonttoStdstring() << std::endl; 
    std::cout << "  初始 IsDirty: " << std::boolalpha << handler.isDirty() << " (预期: false)" << std::endl;

    // 0.1 containsKey (深度递归搜索测试, 直接调用 handler)
    std::cout << "0.1 handler.containsKey (深层简单键搜索):" << std::endl;
    std::cout << "  包含 'name'? " << std::boolalpha << handler.containsKey("name") << std::endl;
    std::cout << "  包含 'street'? " << std::boolalpha << handler.containsKey("street") << std::endl;
    std::cout << "  包含 'math'? " << std::boolalpha << handler.containsKey("math") << std::endl;
    std::cout << "  包含 'nonexistent'? " << std::boolalpha << handler.containsKey("nonexistent") << std::endl;

    std::cout << std::endl;

    // --- 1. 测试扁平化映射(路径键)访问与修改接口 (flatMapAccessor) --- 
    std::cout << "--- 1. 扁平化访问与修改 (flatMapAccessor) --- " << std::endl;
    JsonFlatMapAccessor flatMapAccess = handler.flatMapAccessor(); // 获取访问器

    // 1.1 getValue (只读测试, 依赖缓存)
    std::cout << "1.1 flatMapAccessor().getValue (使用完整路径键):" << std::endl;
    std::string initialCity = flatMapAccess.getValue("mainkey.address.city");
    std::cout << "  读取 mainkey.address.city: \"" << initialCity << "\"" << std::endl;
    std::cout << std::endl;

    // 1.2 getAllValue (只读测试, 依赖缓存)
    std::cout << "1.2 flatMapAccessor().getAllValue (扁平化 map):" << std::endl;
    // ... (getAllValue tests) ...
    // 测试指针重载
    std::cout << "  测试 getAllValue(OutputMap*):" << std::endl;
    std::map<std::string, std::string> resultMapPtr;
    bool getAllPtrSuccess = flatMapAccess.getAllValue(&resultMapPtr);
    std::cout << "    调用 getAllValue(&resultMapPtr): " << std::boolalpha << getAllPtrSuccess << std::endl;
    if (getAllPtrSuccess && !resultMapPtr.empty()) {
        std::cout << "      获取到的 Map 大小: " << resultMapPtr.size() << std::endl;
        // 随机检查几个预期存在的键
        if (resultMapPtr.count("mainkey.name")) {
            std::cout << "      包含 key 'mainkey.name', value: " << resultMapPtr["mainkey.name"] << std::endl;
        } else {
             std::cerr << "      错误: 结果 Map 中未找到 key 'mainkey.name'" << std::endl;
        }
        if (resultMapPtr.count("mainkey.address.city")) { // 此时 city 可能已被修改
             std::cout << "      包含 key 'mainkey.address.city', value: " << resultMapPtr["mainkey.address.city"] << std::endl;
        } else {
             std::cerr << "      错误: 结果 Map 中未找到 key 'mainkey.address.city'" << std::endl;
        }
    } else if (getAllPtrSuccess) {
         std::cout << "      获取到的 Map 为空。" << std::endl;
    } else {
        std::cerr << "    错误: 调用 getAllValue(&resultMapPtr) 失败" << std::endl;
    }

    // 测试传入 nullptr - 已移除，因为 getAllValue(nullptr) 行为已改变
    // std::cout << "    调用 getAllValue(nullptr): ";
    // bool getAllNullSuccess = flatMapAccess.getAllValue(static_cast<std::map<std::string, std::string>*>(nullptr));
    // std::cout << std::boolalpha << getAllNullSuccess << " (预期: true, 如果缓存非空)" << std::endl;

    // 测试 std::optional 重载 (需要 C++17)
    std::cout << "  测试 getAllValue(std::optional<...>)(C++17):" << std::endl;
#ifdef __cpp_lib_optional // 检查是否支持 optional
    std::map<std::string, std::string> resultMapOpt;
    std::optional<std::reference_wrapper<decltype(resultMapOpt)>> optWrapper = resultMapOpt; // 创建 optional 包含引用

    bool getAllOptSuccess = flatMapAccess.getAllValue(optWrapper);
    std::cout << "    调用 getAllValue(optWrapper): " << std::boolalpha << getAllOptSuccess << std::endl;
    if (getAllOptSuccess && !resultMapOpt.empty()) {
        std::cout << "      获取到的 Optional Map 大小: " << resultMapOpt.size() << std::endl;
        // 检查键 (与上面类似)
        if (resultMapOpt.count("mainkey.name")) {
             std::cout << "      包含 key 'mainkey.name', value: " << resultMapOpt["mainkey.name"] << std::endl;
        } else {
             std::cerr << "      错误: Optional 结果 Map 中未找到 key 'mainkey.name'" << std::endl;
        }
    } else if (getAllOptSuccess) {
         std::cout << "      获取到的 Optional Map 为空。" << std::endl;
    } else {
        std::cerr << "    错误: 调用 getAllValue(optWrapper) 失败" << std::endl;
    }

    // 测试传入 std::nullopt
    std::cout << "    调用 getAllValue(std::nullopt): ";
    // 需要显式创建正确类型的空 optional，以便编译器匹配模板
    bool getAllNulloptSuccess = flatMapAccess.getAllValue(std::nullopt);
    std::cout << std::boolalpha << getAllNulloptSuccess << " (预期: true, 如果缓存非空)" << std::endl;
#else
    std::cout << "    (跳过 std::optional 测试, 需要 C++17)" << std::endl;
#endif // __cpp_lib_optional

    // 1.3 测试键发现接口 (getKeys, findKeysByRegex)
    std::cout << "1.3 flatMapAccessor() Key Discovery:" << std::endl;

    // 1.3.1 getKeys()
    std::cout << "  1.3.1 getKeys():" << std::endl;
    std::vector<std::string> allKeys = flatMapAccess.getKeys();
    std::cout << "    发现的总键数: " << allKeys.size() << std::endl;
    if (!allKeys.empty()) {
        std::cout << "    示例键: " << std::endl;
        for (size_t i = 0; i < std::min(allKeys.size(), static_cast<size_t>(5)); ++i) { // 最多打印5个
            std::cout << "      - " << allKeys[i] << std::endl;
        }
        // 验证已知键是否存在
        bool foundName = false;
        bool foundCity = false;
        for(const auto& k : allKeys) {
            if (k == "mainkey.name") foundName = true;
            if (k == "mainkey.address.city") foundCity = true;
        }
        std::cout << "    包含 'mainkey.name'? " << std::boolalpha << foundName << std::endl;
        std::cout << "    包含 'mainkey.address.city'? " << std::boolalpha << foundCity << std::endl;
    }
    std::cout << std::endl;

    // 1.3.2 findKeysByRegex()
    std::cout << "  1.3.2 findKeysByRegex():" << std::endl;
    auto testRegex = [&](const std::string& pattern, const std::string& description) {
        std::cout << "    测试模式: \"" << pattern << "\" (" << description << ")" << std::endl;
        std::vector<std::string> matchedKeys = flatMapAccess.findKeysByRegex(pattern);
        std::cout << "      匹配到的键数: " << matchedKeys.size() << std::endl;
        if (!matchedKeys.empty()) {
            std::cout << "      匹配到的键:" << std::endl;
            for (const auto& key : matchedKeys) {
                std::cout << "        - " << key << std::endl;
            }
        }
        std::cout << std::endl;
    };

    testRegex("mainkey\\.address\\..*", "查找地址下的所有键"); // 需要转义 .
    testRegex(".*city$", "查找以 city 结尾的键");
    testRegex("mainkey\\.scores\\..*", "查找分数下的所有键");
    testRegex("mainkey\\.isAdmin", "查找特定的布尔键");
    testRegex("nonexistentkey.*", "查找不存在的前缀");
    testRegex("[", "测试无效的正则表达式"); // 测试错误处理

    std::cout << std::endl;

    // 1.4 setValueByPath (修改测试)
    std::cout << "1.4 flatMapAccessor().setValueByPath (修改测试):" << std::endl;
    
    bool setResult1 = flatMapAccess.setValueByPath("mainkey.address.city", "新示例市");
    std::cout << "  设置 mainkey.address.city = \"新示例市\": " << std::boolalpha << setResult1 << std::endl;
    if (setResult1) {
        std::cout << "    IsDirty: " << std::boolalpha << handler.isDirty() << " (预期: true)" << std::endl;
        std::cout << "    再次读取 city (测试缓存更新): \"" << flatMapAccess.getValue("mainkey.address.city") << "\"" << std::endl;
    } else {
        std::cerr << "    修改失败，状态未改变。" << std::endl;
    }

    bool setResult2 = flatMapAccess.setValueByPath("mainkey.age", 31);
    std::cout << "  设置 mainkey.age = 31: " << std::boolalpha << setResult2 << std::endl;
     if (setResult2) {
        // currentVersion++; // Removed version tracking
     } // Dirty is already true

    // 测试设置相同的值 (版本号不应增加, Dirty 状态应不变)
    bool wasDirtyBeforeSameSet = handler.isDirty();
    bool setResultSame = flatMapAccess.setValueByPath("mainkey.age", 31); 
    std::cout << "  再次设置 mainkey.age = 31 (相同值): " << std::boolalpha << setResultSame << std::endl;
    std::cout << "    IsDirty: " << std::boolalpha << handler.isDirty() << " (预期: " << std::boolalpha << wasDirtyBeforeSameSet << ", 不变)" << std::endl;

    // 添加新键 (版本号应增加)
    bool setResultNewKey = flatMapAccess.setValueByPath("mainkey.address.country", "中国");
    std::cout << "  添加 mainkey.address.country = \"中国\": " << std::boolalpha << setResultNewKey << std::endl;
    if (setResultNewKey) {
        std::cout << "    IsDirty: " << std::boolalpha << handler.isDirty() << " (预期: true)" << std::endl;
    }

    // 测试无效路径 (不应改变状态)
    bool wasDirtyBeforeInvalid = handler.isDirty();
    bool setResultInvalid = flatMapAccess.setValueByPath("nonexistent.path", "value");
    std::cout << "  设置 nonexistent.path = \"value\": " << std::boolalpha << setResultInvalid << " (预期: false)" << std::endl;
    std::cout << "    IsDirty: " << std::boolalpha << handler.isDirty() << " (预期: " << std::boolalpha << wasDirtyBeforeInvalid << ", 不变)" << std::endl;
    std::cout << std::endl;

    // --- 2. 测试节点访问接口 (nodeAccessor) --- 
    std::cout << "--- 2. 节点访问与修改 (nodeAccessor) --- " << std::endl;
    
    // 2.a 读取测试 (const nodeAccessor)
    std::cout << "2.a 读取测试 (const nodeAccessor):" << std::endl;
    // ... (const access tests remain the same) ...
    {
        const JSONHandler& constHandler = handler; 
        JSONNode constRoot = constHandler.nodeAccessor(); 
        JSONNode constCityNode = constRoot["mainkey"]["address"].get("city");
        std::cout << "  (const) 读取 city (可能已被修改): \"" << constCityNode.asString().value_or("N/A") << "\"" << std::endl;
    }
    std::cout << std::endl;
    
    // 2.b 修改测试 (non-const nodeAccessor 和赋值)
    std::cout << "2.b 修改测试 (non-const nodeAccessor):" << std::endl;
    JSONNode mutableRoot = handler.nodeAccessor(); // 获取可变访问器

    std::cout << "  修改前 IsDirty: " << std::boolalpha << handler.isDirty() << " (预期: true)" << std::endl;

    // 使用赋值运算符修改值
    std::cout << "  使用赋值运算符修改值:" << std::endl;
    std::string oldName = mutableRoot["mainkey"].getStringOrDefault("name", "");
    mutableRoot["mainkey"]["name"] = "修改后的用户";
    std::cout << "    设置 mainkey.name = \"修改后的用户\"" << std::endl;
    std::cout << "      IsDirty: " << std::boolalpha << handler.isDirty() << " (预期: true)" << std::endl;
    
    // 测试赋相同值 (版本不应增加)
    wasDirtyBeforeSameSet = handler.isDirty();
    mutableRoot["mainkey"]["name"] = "修改后的用户";
    std::cout << "    再次设置 mainkey.name = \"修改后的用户\" (相同值)" << std::endl;
    std::cout << "      IsDirty: " << std::boolalpha << handler.isDirty() << " (预期: " << std::boolalpha << wasDirtyBeforeSameSet << ", 不变)" << std::endl;

    // 修改其他值
    mutableRoot["mainkey"]["isAdmin"] = false;
    std::cout << "    设置 mainkey.isAdmin = false" << std::endl;
    std::cout << "      IsDirty: " << std::boolalpha << handler.isDirty() << " (预期: true)" << std::endl;

    // 添加新键
    mutableRoot["mainkey"]["address"]["district"] = "新区域";
    std::cout << "    添加 mainkey.address.district = \"新区域\"" << std::endl;
    std::cout << "      IsDirty: " << std::boolalpha << handler.isDirty() << " (预期: true)" << std::endl;

    // 验证修改结果
    std::cout << "\n    验证修改结果 (通过 mutableRoot):" << std::endl;
    std::cout << "      mainkey.name: \"" << mutableRoot["mainkey"].getStringOrDefault("name", "N/A") << "\"" << std::endl;
    std::cout << "      mainkey.isAdmin: " << std::boolalpha << mutableRoot["mainkey"].getBoolOrDefault("isAdmin", true) << std::endl;
    std::cout << "      mainkey.address.district: \"" << mutableRoot["mainkey"]["address"].getStringOrDefault("district", "N/A") << "\"" << std::endl;
    std::cout << std::endl;

    // --- 3. 跨访问器缓存验证 --- 
    std::cout << "--- 3. 跨访问器缓存验证 --- " << std::endl;
    // 目标: 验证 nodeAccessor 修改后，flatMapAccessor 的缓存会因版本变化而重建

    // 3.1 获取 flatMap 初始值和版本
    JsonFlatMapAccessor flatMapAccess2 = handler.flatMapAccessor(); // 获取新实例或使用旧的
    std::string cityBeforeNodeMod = flatMapAccess2.getValue("mainkey.address.city");
    std::cout << "3.1 flatMap 读取 city: \"" << cityBeforeNodeMod << "\"" << std::endl;

    // 3.2 使用 nodeAccessor 修改 city
    std::string newNodeCityValue = "城市Node修改";
    handler.nodeAccessor()["mainkey"]["address"]["city"] = newNodeCityValue;
    std::cout << "3.2 nodeAccessor 设置 city = \"" << newNodeCityValue << "\"" << std::endl;
    std::cout << "    修改后 IsDirty: " << std::boolalpha << handler.isDirty() << " (预期: true)" << std::endl;

    // 3.3 再次使用 flatMapAccessor 读取 city
    std::string cityAfterNodeMod = flatMapAccess2.getValue("mainkey.address.city");
    std::cout << "3.3 flatMap 再次读取 city: \"" << cityAfterNodeMod << "\" (预期: \"" << newNodeCityValue << "\")" << std::endl;
    if (cityAfterNodeMod != newNodeCityValue) {
        std::cerr << "    错误: flatMapAccessor 未读取到 nodeAccessor 修改后的值！缓存可能未正确失效。" << std::endl;
    }
    std::cout << std::endl;

    // --- 4. 测试文件操作 --- // Renumbered
    std::cout << "--- 4. 测试文件操作 --- " << std::endl;
    std::cout << "  当前 IsDirty: " << std::boolalpha << handler.isDirty() << " (预期: true)" << std::endl;
    std::cout << "4.1 saveToFile:" << std::endl;
    if (handler.saveToFile(testOutputFile)) {
        std::cout << "  成功保存修改后的 JSON 到 " << testOutputFile << std::endl;
        std::cout << "    保存后 IsDirty: " << std::boolalpha << handler.isDirty() << " (预期: false)" << std::endl;
    } else {
        std::cerr << "  保存到 " << testOutputFile << " 失败！" << std::endl;
    }
    std::cout << std::endl;

    // --- 5. 测试状态管理 --- // Renumbered
    std::cout << "--- 5. 测试状态管理 --- " << std::endl;

    // 5.1 clear:
    std::cout << "5.1 clear:" << std::endl;
    handler.clear();
    std::cout << "  调用 clear() 后，主键: \"" << handler.getMainKey() << "\"" << std::endl;
    std::cout << "  clear() 后，nodeAccessor() 是否为 null? " << std::boolalpha << handler.nodeAccessor().isNull() << std::endl;
    std::cout << "  clear() 后 IsDirty: " << std::boolalpha << handler.isDirty() << " (预期: false)" << std::endl;
    std::cout << std::endl;

    // 5.2 reset:
    std::cout << "5.2 reset (重新加载原始文件):" << std::endl;
    if (handler.reset(&originalFilePath)) {
        std::cout << "  成功使用 reset 从 " << originalFilePath << " 重新加载。" << std::endl;
        JSONNode resetRoot = handler.nodeAccessor(); // Use const accessor is fine here
        std::cout << "    reset 后，mainkey.name: \"" << resetRoot["mainkey"].getStringOrDefault("name", "N/A") << "\"" << std::endl;
        std::cout << "    reset 后 IsDirty: " << std::boolalpha << handler.isDirty() << " (预期: false)" << std::endl;
    } else {
         std::cerr << "  使用 reset 从 " << originalFilePath << " 重新加载失败！" << std::endl;
    }
    std::cout << std::endl;

    // 5.3 测试 loadFromJsonFile (类似 reset)
    std::cout << "5.3 loadFromJsonFile (再次加载原始文件):" << std::endl;
     if (handler.loadFromJsonFile(originalFilePath)) {
        std::cout << "  成功再次加载 " << originalFilePath << std::endl;
        std::cout << "    load 后 IsDirty: " << std::boolalpha << handler.isDirty() << " (预期: false)" << std::endl;
    } else {
         std::cerr << "  再次加载 " << originalFilePath << " 失败！" << std::endl;
    }
    std::cout << std::endl;


    // --- 6. 其他文件创建 (可选 C++17) --- // Renumbered
    std::cout << "--- 6. 其他文件创建 ---" << std::endl;
     // Create config file tests (no state change checks needed here as they use a separate handler instance implicitly)
    JSONHandler creator; // Use a separate instance for creation tests

    // 6.1 测试 createConfigJsonFile(const nlohmann::json&)
    const std::string testCreatedByJsonFile = "test_created_by_json.json";
    std::cout << "6.1 测试 createConfigJsonFile(json):" << std::endl;
    nlohmann::json directJson = {
        {"server", {{"ip", "192.168.0.1"}, {"port", 8080}}},
        {"features", {"auth", true}, {"logging", "debug"}}
    };
    if (creator.createConfigJsonFile(testCreatedByJsonFile, directJson)) {
        std::cout << "  成功创建文件: " << testCreatedByJsonFile << std::endl;
    } else {
        std::cerr << "  创建文件失败: " << testCreatedByJsonFile << std::endl;
    }

    // 6.2 测试 createConfigFromPathMap(const std::map<...>&)
    const std::string testCreatedByPathMapFile = "test_created_by_pathmap.json";
    std::cout << "\n6.2 测试 createConfigFromPathMap(map):" << std::endl;
    std::map<std::string, std::string> pathMap = {
        {"database.host", "localhost"},
        {"database.port", "5432"},
        {"database.user", "tester"},
        {"logging.file", "/var/log/app.log"},
        {"logging.level", "warning"}
    };
    if (creator.createConfigFromPathMap(testCreatedByPathMapFile, pathMap)) {
        std::cout << "  成功创建文件: " << testCreatedByPathMapFile << std::endl;
    } else {
        std::cerr << "  创建文件失败: " << testCreatedByPathMapFile << std::endl;
    }


    // 6.3 测试 createRNGJsonFile (C++17)
    const std::string testRngFile = "test_rng.json";
    std::cout << "\n6.3 测试 createRNGJsonFile (C++17):" << std::endl;
    try {
        creator.createRNGJsonFile(testRngFile, 1024, 5); // Create a small random file
        std::cout << "  成功创建随机文件: " << testRngFile << " (大小上限 1KB, 深度上限 5)" << std::endl;
    } catch (const std::exception& e) {
        std::cerr << "  创建随机文件时出错: " << e.what() << std::endl;
    }

    std::cout << std::endl;

    std::cout << "\n===== JSONHandler 功能测试结束 =====\n" << std::endl;
}

/**
 * @brief 测试 ThreadPool 的核心功能。
 *
 * 该函数演示了:
 * - 创建 ThreadPool 实例。
 * - 使用 enqueue() 提交默认优先级的任务 (返回 void 和返回值的任务)。
 * - 使用 enqueueWithPriority() 提交不同优先级的任务。
 * - 使用 std::future 获取任务结果。
 * - 观察 getWorkingThreadCount() 的变化。
 * - 隐式测试线程池的析构和线程 join。
 */
void testThreadPoolFeatures() {
    std::cout << "\n===== 开始测试 ThreadPool 功能 =====\n" << std::endl;

    const size_t numThreads = 4;
    ThreadPool pool(numThreads);
    std::cout << "  创建了包含 " << numThreads << " 个线程的 ThreadPool。" << std::endl;

    std::vector<std::future<int>> futures_int;
    std::vector<std::future<std::string>> futures_string;
    std::vector<std::future<void>> futures_void;

    // 清空上次测试的日志
    {
        std::lock_guard<std::mutex> lock(g_logMutex);
        g_taskExecutionLog.clear();
    }
    auto startTimeRef = std::chrono::high_resolution_clock::now(); // 参考起始时间

    // 增加任务数量
    const int numTasksPerPrio = 20; // 每个优先级提交的任务数
    const int defaultPriority = 0;
    const int highPriority = -10;
    const int midPriority = 5;
    const int lowPriority = 10;

    // --- 1. 提交默认优先级任务 (enqueue) --- 
    std::cout << "\n--- 1. 提交默认优先级任务 (enqueue, prio=" << defaultPriority << ") --- " << std::endl;
    for (int i = 0; i < numTasksPerPrio; ++i) {
        futures_int.emplace_back(pool.enqueue([i, defaultPriority, startTimeRef] {
            auto now = std::chrono::high_resolution_clock::now();
            {
                std::lock_guard<std::mutex> lock(g_logMutex);
                g_taskExecutionLog.push_back({defaultPriority, now, std::this_thread::get_id()});
            }
            std::this_thread::sleep_for(std::chrono::milliseconds(std::rand() % 10 + 5)); // 随机短时间睡眠
            return i * i;
        }));
    }
    std::cout << "  提交了 " << numTasksPerPrio << " 个默认优先级任务。" << std::endl;

    // --- 2. 提交带优先级的任务 (enqueueWithPriority) --- 
    std::cout << "\n--- 2. 提交带优先级的任务 --- " << std::endl;

    // 高优先级任务 (priority = -10)
    std::cout << "  提交高优先级任务 (prio=" << highPriority << ")..." << std::endl;
    for (int i = 0; i < numTasksPerPrio; ++i) {
        futures_int.emplace_back(pool.enqueueWithPriority(highPriority, [i, highPriority, startTimeRef] {
             auto now = std::chrono::high_resolution_clock::now();
            {
                std::lock_guard<std::mutex> lock(g_logMutex);
                g_taskExecutionLog.push_back({highPriority, now, std::this_thread::get_id()});
            }
            std::this_thread::sleep_for(std::chrono::milliseconds(std::rand() % 10 + 5));
            return 1000 + i;
        }));
    }

    // 中优先级任务 (priority = 5)
    std::cout << "  提交中优先级任务 (prio=" << midPriority << ")..." << std::endl;
     for (int i = 0; i < numTasksPerPrio; ++i) {
        futures_void.emplace_back(pool.enqueueWithPriority(midPriority, [i, midPriority, startTimeRef] {
            auto now = std::chrono::high_resolution_clock::now();
            {
                std::lock_guard<std::mutex> lock(g_logMutex);
                g_taskExecutionLog.push_back({midPriority, now, std::this_thread::get_id()});
            }
            std::this_thread::sleep_for(std::chrono::milliseconds(std::rand() % 10 + 5));
        }));
    }

    // 低优先级任务 (priority = 10)
    std::cout << "  提交低优先级任务 (prio=" << lowPriority << ")..." << std::endl;
    for (int i = 0; i < numTasksPerPrio; ++i) {
        futures_int.emplace_back(pool.enqueueWithPriority(lowPriority, [i, lowPriority, startTimeRef] {
            auto now = std::chrono::high_resolution_clock::now();
            {
                std::lock_guard<std::mutex> lock(g_logMutex);
                g_taskExecutionLog.push_back({lowPriority, now, std::this_thread::get_id()});
            }
            std::this_thread::sleep_for(std::chrono::milliseconds(std::rand() % 10 + 5));
            return -1000 - i;
        }));
    }

    // 提交一个 string 任务用于测试 (可选)
    // futures_string.emplace_back(pool.enqueue([] { ... }));

    std::cout << "  所有任务提交完毕，工作线程数: " << pool.getWorkingThreadCount() << std::endl;

    // --- 3. 获取任务结果 (等待所有任务完成) --- 
    std::cout << "\n--- 3. 获取任务结果 (调用 future.get()) --- " << std::endl;
    std::cout << "  (这将阻塞直到每个任务完成)" << std::endl;

    int sum = 0;
    std::cout << "  获取 int 结果: ";
    for (auto& fut : futures_int) {
        int result = fut.get();
        std::cout << result << " ";
        sum += result;
    }
    std::cout << " | 总和: " << sum << std::endl;

    std::cout << "  获取 string 结果: ";
    for (auto& fut : futures_string) {
        std::cout << "\"" << fut.get() << "\" ";
    }
    std::cout << std::endl;

    std::cout << "  等待 void 任务完成: ";
    for (auto& fut : futures_void) {
        fut.get(); // .get() on void future waits for completion
    }
    std::cout << "完成." << std::endl;

    std::cout << "\n  所有任务完成后，工作线程数: " << pool.getWorkingThreadCount() << " (预期: 0)" << std::endl;

    // --- 4. 分析优先级执行顺序 (基于记录的开始时间) --- 
    std::cout << "\n--- 4. 分析优先级执行情况 --- " << std::endl;
    {
        std::lock_guard<std::mutex> lock(g_logMutex);
        if (g_taskExecutionLog.empty()) {
            std::cout << "  没有记录到任务执行信息。" << std::endl;
        } else {
            std::cout << "  记录到的任务总数: " << g_taskExecutionLog.size() << std::endl;

            // 按优先级分组计算平均启动时间 (相对于参考点 startTimeRef)
            std::map<int, std::vector<double>> startTimesByPriority;
            for (const auto& log : g_taskExecutionLog) {
                auto duration = std::chrono::duration_cast<std::chrono::microseconds>(log.startTime - startTimeRef);
                startTimesByPriority[log.priority].push_back(static_cast<double>(duration.count()));
            }

            std::cout << "  各优先级任务平均启动时间 (微秒, 相对于开始):" << std::endl;
            // 按优先级排序输出 (map 默认按 key 排序)
            for (const auto& pair : startTimesByPriority) {
                int priority = pair.first;
                const auto& times = pair.second;
                if (!times.empty()) {
                    double sum = std::accumulate(times.begin(), times.end(), 0.0);
                    double average = sum / times.size();
                    // 找到第一个和最后一个任务的启动时间
                    double minTime = *std::min_element(times.begin(), times.end());
                    double maxTime = *std::max_element(times.begin(), times.end());
                    std::cout << "    优先级: " << priority 
                              << ", 任务数: " << times.size()
                              << ", 平均启动: " << average << " us" 
                              << ", 最早启动: " << minTime << " us" 
                              << ", 最晚启动: " << maxTime << " us" << std::endl;
                }
            }
            std::cout << "  (注意: 平均启动时间受任务数量、线程数、任务耗时和系统调度影响，" << std::endl;
            std::cout << "   数值越小的优先级越高，预期其平均启动时间相对更早)" << std::endl;
        }
    }

    // 可以在这里添加更多测试，例如大量任务提交等

    std::cout << "\n===== ThreadPool 功能测试结束 =====\n" << std::endl;
    // 当 pool 在函数结束时销毁，会自动调用析构函数，停止并 join 所有工作线程
}

int main(int argc, char* argv[]) {
    std::cout << "程序启动..." << std::endl;

    const std::string testInputFile = "test_config.json"; // 临时输入文件
    const std::string testCreatedByJsonFile = "test_created_by_json.json";
    const std::string testCreatedByPathMapFile = "test_created_by_pathmap.json";
    const std::string testRngFile = "test_rng.json";
    const std::string testCreatedInMemoryFile = "test_created_in_memory.json"; // New test file

    // --- 测试准备: 创建临时 JSON 文件 ---
    std::cout << "\n--- 测试准备 ---" << std::endl;
    const std::string sampleJsonData = R"({
        "mainkey": {
            "name": "测试用户",
            "age": 30,
            "isAdmin": true,
            "address": {
                "street": "人民路123号",
                "city": "示例市",
                "zip": "100000"
            },
            "skills": ["C++", "JSON", "测试"],
            "nullableValue": null,
            "scores" : {
                "math": 95,
                "english": 88.5
            }
        }
    })";

    std::ofstream outFile(testInputFile);
    if (!outFile) {
        std::cerr << "错误：无法创建临时测试文件 " << testInputFile << std::endl;
        return 1;
    }
    outFile << sampleJsonData;
    outFile.close();
    std::cout << "成功创建临时测试文件: " << testInputFile << std::endl;


    // --- JSONHandler 测试 ---
    std::cout << "\n--- JSONHandler 测试 ---" << std::endl;
    JSONHandler handler; // non-const handler instance

    // 使用 loadFromJsonFile 初始化
    if (handler.loadFromJsonFile(testInputFile)) {
        std::cout << "JSONHandler 使用 loadFromJsonFile 初始化成功。" << std::endl;
        // 调用核心测试函数 (passes non-const handler)
        testJsonHandlerFeatures(handler, testInputFile); 
    } else {
        std::cerr << "JSONHandler 使用 loadFromJsonFile(" << testInputFile << ") 初始化失败！" << std::endl;
        // 清理临时文件
        std::remove(testInputFile.c_str());
        return 1;
    }

    // --- 测试: 内存中创建并保存 --- 
    std::cout << "\n--- 测试: 内存中创建并保存 ---" << std::endl;
    {
        JSONHandler memoryHandler; // 使用默认构造函数
        std::cout << "  创建空的 JSONHandler." << std::endl;
        
        // 检查初始状态
        std::cout << "    初始 IsDirty: " << std::boolalpha << memoryHandler.isDirty() << " (预期: false)" << std::endl;
        std::cout << "    初始是否为 null? " << std::boolalpha << memoryHandler.nodeAccessor().isNull() << std::endl;

        // 获取可变节点并构建数据
        JSONNode root = memoryHandler.nodeAccessor();
        std::cout << "  获取可变节点并添加数据..." << std::endl;
        root["project"] = "内存测试";
        root["version"] = 1.0;
        root["modules"] = nlohmann::json::array({"core", "utils", "network"});
        root["config"]["enabled"] = true;
        root["config"]["retries"] = 5;

        // 检查修改后的状态
        std::cout << "    修改后 IsDirty: " << std::boolalpha << memoryHandler.isDirty() << " (预期: true)" << std::endl;
        std::cout << "    修改后 JSON: \n" << memoryHandler.getJsonttoStdstring(2) << std::endl; // Print with indent

        // 保存到文件
        std::cout << "  保存到文件: " << testCreatedInMemoryFile << std::endl;
        if (memoryHandler.saveToFile(testCreatedInMemoryFile)) {
            std::cout << "    保存成功." << std::endl;
            std::cout << "    保存后 IsDirty: " << std::boolalpha << memoryHandler.isDirty() << " (预期: false)" << std::endl;
            // 可以选择性地添加读取验证
            JSONHandler checker(testCreatedInMemoryFile); // Use constructor to load
            if (!checker.nodeAccessor().isNull()) {
                 std::cout << "    读取验证: project = '" << checker.nodeAccessor()["project"].asString().value_or("N/A") << "'" << std::endl;
            } else {
                 std::cerr << "    错误: 无法重新加载已保存的文件进行验证!" << std::endl;
            }
        } else {
            std::cerr << "    保存失败!" << std::endl;
        }
    }
    std::cout << "--- 内存中创建并保存 测试结束 ---" << std::endl;


    // --- ThreadPool 测试 --- 
    testThreadPoolFeatures();


    // --- 其他测试代码 (可选) ---
    // Example: Exceptionhandler test
    // std::cout << "\n--- Exceptionhandler 测试 ---" << std::endl;
    // Exceptionhandler& exHandler = Exceptionhandler::get_instance();
    // exHandler.bindingFailureSignalHandler(customSignalHandler);
    // std::cout << "注册信号处理程序..." << std::endl;
    // sleep(5); // 等待信号


    // --- 清理临时文件 ---
    std::cout << "\n--- 清理测试文件 ---" << std::endl;
    if (std::remove(testInputFile.c_str()) == 0) {
        std::cout << "成功删除: " << testInputFile << std::endl;
    } else {
        std::cerr << "删除失败: " << testInputFile << std::endl;
    }
    // Add cleanup for other created files (test_output.json, etc.) if desired
    std::remove("test_output.json");
    std::remove(testCreatedByJsonFile.c_str());     // Cleanup for createConfigJsonFile(json)
    std::remove(testCreatedByPathMapFile.c_str()); // Cleanup for createConfigFromPathMap
    std::remove(testCreatedInMemoryFile.c_str());  // Cleanup for in-memory creation test
    std::remove("test_created_config.json"); // Keep if still used/needed
    std::remove("test_custom_config.json"); // Keep if still used/needed
    std::remove(testRngFile.c_str()); // Cleanup for createRNGJsonFile


    std::cout << "\n程序正常结束。" << std::endl;
    return 0;
}